package com.jiexin.service;

import com.jiexin.beans.DescPageQuery;
import com.jiexin.beans.DescPageResult;
import com.jiexin.common.RequestHolder;
import com.jiexin.dao.PlmDescriptionMapper;
import com.jiexin.exception.ParamException;
import com.jiexin.model.PlmDescription;
import com.jiexin.param.DescriptionParam;
import com.jiexin.util.BeanValidator;
import com.jiexin.util.IpUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author: Jay_Liu
 * @Description:
 * @Date: Created in 21:00 2018/5/28 0028
 * @Modified By:
 */
@Service
public class PlmDescriptionService {

    @Resource
    PlmDescriptionMapper descriptionMapper;

    public void save(DescriptionParam param) {
        BeanValidator.check(param);
        if(checkAttrNameIsExist(param.getItemType(), param.getAttrName())) {
            throw new ParamException("类型["+param.getItemType()+"],该属性名称已存在");
        }
        if(checkAttrIdIsExist(param.getItemType(), param.getAttrId())) {
            throw new ParamException("类型["+param.getItemType()+"],该ID已存在");
        }
        if(checkSeqIsExist(param.getItemType(), param.getSeq())) {
            throw new ParamException("类型["+param.getItemType()+"],该顺序已存在");
        }
        PlmDescription description  = PlmDescription.builder().itemType(param.getItemType()).attrName(param.getAttrName())
                .attrId(param.getAttrId()).seq(param.getSeq()).remark(param.getRemark()).status(param.getStatus()).build();
        description.setOperator(RequestHolder.getCurrentUser().getUsername());
        description.setOperateTime(new Date());
        description.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        descriptionMapper.insertSelective(description);
    }

    public void update(DescriptionParam param) {

    }

    public void delete(List<Integer> descriptionIds) {

    }

    private boolean checkSeqIsExist(String itemType, Integer seq) {
        return descriptionMapper.countByItemTypeAndSeq(itemType, seq) > 0 ;
    }

    private boolean checkAttrIdIsExist(String itemType, Integer attrId) {
        return descriptionMapper.countByItemTypeAndAttrId(itemType, attrId) > 0 ;
    }

    private boolean checkAttrNameIsExist(String itemType, String attrName) {
        return descriptionMapper.countByItemTypeAndAttrName(itemType, attrName) > 0 ;
    }

    public DescPageResult<PlmDescription> getPage(DescPageQuery page) {
        int count = descriptionMapper.count(page);
        if (count > 0) {
            List<PlmDescription> descriptionList = descriptionMapper.getPage(page);
            return DescPageResult.<PlmDescription>builder().rows(descriptionList).total(count).build();
        }
        return DescPageResult.<PlmDescription>builder().build();
    }
}
